<?php
class VideoController extends BaseController {
    public function actionList() {
        $pid = Yii::app()->request->getParam('pid');
        if (empty($pid)) {
            $this->error('参数非法');
        }
        $sub_floder = Floder::model()->findByPk($pid);   //子目录
        if ($sub_floder === null) {
            $this->error('子相册不存在');
        }
        //获取1级目录
        $parent_floder = Floder::model()->findByPk($sub_floder->pid);
        if ($sub_floder === null) {
            $this->error('主相册不存在');
        }

        $video = Video::model();
        $video->pid = $pid;

        $limit = intval(Yii::app()->request->getPost('limit', 12));
        $page = intval(Yii::app()->request->getPost('page', 1));  //默认获取第一页数据
        $page_list = $video->getPageList($page, $limit);
        if ($page_list === false) {
            $this->error($video->getError('page'));
        }

        if (Yii::app()->request->isAjaxRequest) {
            $this->jsonResponse($page_list);
        } else {
            $view_params = array(
                'pid' => $pid,
                'page_list' => $page_list,
                'sub_floder' => $sub_floder,
                'parent_floder' => $parent_floder,
            );
            $this->render('list', $view_params);
        }
    }

    /**
     * 上传视频
     */
    public function actionUpload() {
        if (!Yii::app()->request->isAjaxRequest || !Yii::app()->request->isPostRequest) {
            return;
        }
        $pid = Yii::app()->request->getQuery('pid');
        if (empty($pid)) {
            $this->error('参数非法');
        }

        $video = new Video();
        $is_success = $video->upload();
        if ($is_success === false) {
            $this->error($video->getErrors());
        }
        $is_success = $video->videoAdd($pid);
        if ($is_success === false) {
            $this->error($video->getErrors());
        }
        $this->success('添加成功');
    }

    /**
     * 批量删除
     */
    public function actionBatchDelete() {
        if (Yii::app()->request->isAjaxRequest) {
            $id_list = Yii::app()->request->getPost('id_list');
            if (empty($id_list)) {
                $this->error('参数非法');
            }
            $video_list = Video::model()->findAllByPk($id_list);
            if (empty($video_list)) {
                $this->error('不存在的记录');
            }
            $total = count($video_list);
            $fail = 0;
            foreach ($video_list as $video) {
                $is_success = $video->remove();
                if (!$is_success) {
                    $fail++;
                }
            }
            $success = $total-$fail;
            $msg = "总共{$total}个,成功{$success}个，失败{$fail}";
            $this->success($msg);
        }
    }
}